package org.clipjoint.controller;

import com.alibaba.fastjson.JSON;
import org.clipjoint.entity.EmailCode;
import org.clipjoint.entity.Purchased;
import org.clipjoint.entity.User;
import org.clipjoint.entity.Dream;
import org.clipjoint.service.UserService;
import org.clipjoint.service.impl.UserServiceImpl;
import org.clipjoint.vo.JsonResult;


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/user")
public class UserController extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String method = request.getParameter("method");

        switch (method) {
            case "checkEmail":
                checkEmail(request, response);
                break;
            case "register":
                register(request, response);
                break;
            case "login":
                login(request, response);
                break;
            case "logout":
                logout(request, response);
                break;
            case "updateInfo":
                updateInfo(request, response);
                break;
            case "updatePassword":
                updatePassword(request, response);
                break;
            case "dream":
                dream(request, response);
                break;
            case "purchased":
                purchased(request, response);
                break;
            case "gamefactory":
                gamefactory(request, response);
                break;
            case "wallet":
                wallet(request, response);
                break;
            default:
                break;
        }

    }

    private void wallet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        // 获取在线用户
        User onlineUser = (User) session.getAttribute("onlineUser");
        Long id = onlineUser.getId();

        List<Purchased> purchasedList = null;

        try {
            purchasedList = userService.purchased(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        request.setAttribute("purchasedList", purchasedList);
        request.getRequestDispatcher("/setting/wallet.jsp").forward(request, response);
    }

    private void gamefactory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        // 获取在线用户
        User onlineUser = (User) session.getAttribute("onlineUser");
        Long id = onlineUser.getId();

        List<Purchased> purchasedList = null;

        try {
            purchasedList = userService.purchased(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        request.setAttribute("purchasedList", purchasedList);
        request.getRequestDispatcher("/setting/gamefactory.jsp").forward(request, response);
    }

    private void purchased(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        // 获取在线用户
        User onlineUser = (User) session.getAttribute("onlineUser");
        Long id = onlineUser.getId();

        List<Purchased> purchasedList = null;

        try {
            purchasedList = userService.purchased(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        request.setAttribute("purchasedList", purchasedList);
        request.getRequestDispatcher("/setting/purchased.jsp").forward(request, response);
    }

    private void dream(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        // 获取在线用户
        User onlineUser = (User) session.getAttribute("onlineUser");
        Long id = onlineUser.getId();

        List<Dream> dreamList = null;

        try {
            dreamList = userService.dream(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        request.setAttribute("dreamList", dreamList);
        request.getRequestDispatcher("/setting/dream.jsp").forward(request, response);

    }

    private void updatePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();

        // 获取在线用户
        User onlineUser = (User) session.getAttribute("onlineUser");
        onlineUser.setPassword(request.getParameter("password"));

        // 调用service修改用户信息
        int result = 0;
        try {
            result = userService.updateInfo(onlineUser);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 判断修改结果
        if (result == 1) {
            session.removeAttribute("onlineUser");
            response.getWriter().print(JsonResult.builder().code(0).msg("修改成功！").build().toJsonString());
        } else {
            response.getWriter().print(JsonResult.builder().code(1).msg("修改失败！").build().toJsonString());
        }
    }

    private void updateInfo(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        HttpSession session = request.getSession();

        // 获取在线用户
        User onlineUser = (User) session.getAttribute("onlineUser");
        onlineUser.setUsername(request.getParameter("username"));

        // 调用service修改用户信息
        int result = 0;
        try {
            result = userService.updateInfo(onlineUser);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 判断修改结果
        if (result == 1) {
            // 重新获取用户信息并保存到session
            session.setAttribute("onlineUser", onlineUser);
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            request.getRequestDispatcher("/setting/info.jsp").forward(request, response);
        }
    }

    private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession();

        // 清除session
        session.removeAttribute("onlineUser");

        // 删除浏览器上已有的cookie
        Cookie cookie = new Cookie("onlineUser", "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        // 重定向到登录页
        response.sendRedirect(request.getContextPath() + "/index.jsp");
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        // session
        HttpSession session = request.getSession();

        // 获取表单数据
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");

        // 将数据封装到实体类
        User user = User.builder().email(email).password(password).build();

        // 调用UserService登录业务方法
        User result = null;
        try {
            result = userService.login(user);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 判断结果
        if (result != null) {
            // 将当前用户存入session
            session.setAttribute("onlineUser", result);

            // 判断是否免登录
            Cookie cookie;
            if ("true".equals(rememberMe)) {
                // 创建cookie保存用户信息
                cookie = new Cookie("onlineUser", URLEncoder.encode(JSON.toJSONString(result), "utf-8"));
                cookie.setPath("/");
                cookie.setMaxAge(30 * 24 * 60 * 60);
            } else {
                // 删除浏览器上已有的cookie
                cookie = new Cookie("onlineUser", "");
                cookie.setPath("/");
                cookie.setMaxAge(0);
            }
            response.addCookie(cookie);
            response.getWriter().print(JsonResult.builder().code(0).msg("登录成功").build().toJsonString());
        } else {
            request.setAttribute("msg", "用户名或者密码错误！");
            request.getRequestDispatcher("/user/login.jsp").forward(request, response);
        }
    }

    private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();

        //获取表单数据
        String email = request.getParameter("email");
        String code = request.getParameter("code");
        String password = request.getParameter("password");
        String image = "/static/image/default-image.png";

        EmailCode emailRegisterCode = (EmailCode) session.getAttribute("emailRegisterCode");
        if (!email.equals(emailRegisterCode.getEmail())) {
            request.setAttribute("msg", "请使用对应邮箱的验证码！");
            request.getRequestDispatcher("/user/register.jsp").forward(request, response);
            return;
        } else if (!code.equalsIgnoreCase(emailRegisterCode.getCode())) {
            request.setAttribute("msg", "邮箱验证码错误！");
            request.getRequestDispatcher("/user/register.jsp").forward(request, response);
            return;
        } else {
            session.removeAttribute("emailRegisterCode");
        }

        // 将数据封装到实体类
        User user = User.builder().email(email).password(password).image(image).build();

        // 调用UserService的注册业务方法
        int result = 0;
        try {
            result = userService.register(user);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 判断结果
        if (result == 1) {
            response.sendRedirect(request.getContextPath() + "/user/login.jsp");
        } else {
            request.setAttribute("msg", "注册失败！");
            request.getRequestDispatcher("/user/register.jsp").forward(request, response);
        }

    }

    private void checkEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取表单数据
        String email = request.getParameter("email");

        boolean result = false;
        try {
            result = userService.checkEmail(email);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (result) {
            response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(0).build()));
        } else {
            response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(1).build()));
        }
    }



    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request,response);

    }
}
